package com.ding.easycontroller.work;


import lombok.Data;

import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Data
public class Dao extends Script {

    {
        setType("dao");
    }

    //名称
    private String name;

    private static Pattern modulePattern = Pattern.compile("function[ \t\n]*_dao[ \t\n]*\\([ \t\n]*\\)");

    private ScriptEngine scriptEngine;

    private String initJs;

    //创建服务
    public void doInit() {
        if (initJs == null) {
            preInit();
        }
        try {
            scriptEngine.eval(initJs);
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doDestroy() {
        try {
            scriptEngine.eval("delete daos." + name);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void preInit() {
        Matcher matcher = modulePattern.matcher(js);
        if (!matcher.find()) {
            throw new RuntimeException("没有_dao方法");
        }

        String functionName = "dao_" + id;
        String pre = "function " + functionName + "(){";
        String post = "\nreturn _dao()}\n" + "daos." + name + "=" + functionName + "();";
        initJs = pre + js + post;
    }

    public boolean equals(Object obj) {
        return super.equals(obj);
    }

}
